import React, { useState, useEffect, Form ,useRef} from 'react';//useRef用于获取输入内容
import { Table, Space, Button, Popconfirm, message,Pagination } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
// import "./user.css"
import Axios from "axios"


const Index = () => {
  const navigate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState([]);//表格的数据
  const [searchName,setSearchName] = useState("");//查询的name
  const [current,setCurrent]=useState(1)//当前页
  const [total,setTotal]=useState(0);//总条数
  const [pageSize,setPageSize]=useState(10);//界面显示条数
  const searchNameRef=useRef(null);
  const searchContactRef=useRef(null);
  const searchEmailRef=useRef(null);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
    },
    {
      title: '费用',
      dataIndex: 'cost',
    },
    {
      title: '花费项',
      dataIndex: 'way',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (        //render函数 ，第二个参数record，即为当行的数据
        <Space size="middle">
          <Button type='default' onClick={() => handleEdit(record._id)}>修改</Button>
          <Popconfirm
            title="确认框"
            description="是否确认删除?"
            onConfirm={() => delClient(record._id)}
            onCancel={cancel_del}
            okText="确定"
            cancelText="取消"
            icon={
              <QuestionCircleOutlined
                style={{
                  color: 'red',
                }}
              />
            }
          >

            <Button type='primary' danger >删除</Button>
          </Popconfirm>

          <Button disabled block onClick={() => handleDel(record.key)}>更多</Button>
        </Space>
      ),
    },
  ];


  useEffect(() => {
    GetDataList();
  }, [current]) //当current改变时才加载GetDataList()
  //2.请求得到的数据放到data中
  function GetDataList(num=1) {
    //1.向数据库发起一个请求
    Axios.get("http://localhost:3000/finance/list",{
      params:{//这里是传到服务器的
        date:searchNameRef.current.value,
        cost:searchContactRef.current.value,
        way:searchEmailRef.current.value,
        current:current,
        pageSize:pageSize

      }
    }).then((res) => {
      console.log("response data", res.data);
      setData(res.data.data);
      setTotal(res.data.count)
    }).catch((err) => {
      console.log("err", err);
    });
  }

  // function handleDel(key) {
  //   //1.提示用户是否删除
  //   //2.如果点击确定 才删除

  // }
  function delClient(_id) {
    console.log("_id", _id);
    //向服务器发起删除的请求
    Axios.get("http://localhost:3000/finance/del", {
      params: { "_id": _id }
    }).then((res) => {
      console.log(res)
      if (res.data.code == 0) {
        GetDataList();//重新渲染，相当于自刷新
        message.success(res.data.message);//删除成功
      }
      else {
        message.info(res.data.message);//删除失败
      }
    }).catch((err) => {
      console.log(err);
      message.error("服务器异常");
    })
    //将响应回来的数据返回给用户  提示给用户
    // message.success("成功")
  }

  function handleEdit(key) {
    //跳转到修改页面
    navigate("/home/finance/add?id=" + key);
  }

  function cancel_del() {
    message.success("取消成功")
  }
  //查询
  function searchList() {
    //setSearchName(searchNameRef.current.value);
    GetDataList();//显示table的数据
  }
  function handleChangePage(num,size){
    setCurrent(num);
    GetDataList();
  }

  return (
<>
  <div style={{ marginBottom: '10px', display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
    <div style={{ marginRight: '10px' }}>
      <input ref={searchNameRef} placeholder="请输入日期" style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }} />
    </div>
    <div style={{ marginRight: '10px' }}>
      <input ref={searchContactRef} placeholder="请输入金额" style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }} />
    </div>
    <div style={{ marginRight: '10px' }}>
      <input ref={searchEmailRef} placeholder="请输入花费项" style={{ marginBottom: '10px', padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }} />
    </div>
    <Button onClick={searchList} style={{ padding: '16px 16px', borderRadius: '4px', background: '#007bff', color: '#fff', border: 'none' }}>查询</Button>
  </div>
  <Table pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} style={{ border: '1px solid #ccc', borderRadius: '4px', padding: '10px', boxShadow: '0 0 10px rgba(0,0,0,0.1)' }} />
  <Pagination 
  total={total} 
  pageSize={pageSize} 
  current={current}
  onChange={handleChangePage}/>
</>

  );
};
export default Index;